package test.ground.netty.netty.my;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 解码
 * @author wangshaopeng
 */
public class MessageDecoder extends LengthFieldBasedFrameDecoder {

    //头部信息的大小应该是 byte+byte+int = 1+8+4 = 14
    private static final int HEADER_SIZE = 13;

    public MessageDecoder() {
        super(1<<20, 9, 4);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        if (in == null) {
            return null;
        }

        if (in.readableBytes() <= HEADER_SIZE) {
            return null;
        }

        in.markReaderIndex();

        byte type = in.readByte();
        long requestId = in.readLong();
        int dataLength = in.readInt();

        // 如果dataLength过大，可能导致问题
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return null;
        }

        byte[] data = new byte[dataLength];
        in.readBytes(data);

        return new Message(type, requestId, data);
    }
}